//
// Created by jingyuewu on 25-8-17.
//
#include "boost/asio.hpp"
#include <ctime>
#include <iostream>

int main(int argc, char *argv[]) {
  int port = 17239;
  std::string host = "127.0.0.1";
  try {
    // if (argc != 2) {
    //   std::cerr << "Usage: client <host>" << std::endl;
    //   return 1;
    // }
    boost::asio::io_context io_context;
    boost::asio::ip::tcp::resolver resolver(io_context);

    boost::asio::ip::tcp::resolver::results_type endpoints =
        resolver.resolve(host, std::to_string(port));
    std::cout << "connecting to " << host << ":" << std::to_string(port)
              << std::endl;

    boost::asio::ip::tcp::socket sock(io_context);

    for (;;) {
      std::array<char, 128> buf;
      boost::system::error_code error;

      boost::asio::connect(sock, endpoints);
      std::cout << "connected" << std::endl;

      size_t len = sock.read_some(boost::asio::buffer(buf), error);

      if (error == boost::asio::error::eof) {
        std::cout << "read done" << std::endl;
      } else if (error) {
        throw boost::system::system_error(error);
      }

      std::cout.write(buf.data(), len);
      std::cout.flush();
      // sleep(1);
    }
  } catch (std::exception &e) {
    std::cerr << e.what() << std::endl;
  }
  return 0;
}